package com.bstek.pms.tools.utils;

import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @Description 弹窗工具类
 * @Author zhangkun
 * @CreateDate 2020/8/1
 */
public class AlertUtils {


    /**
     * 弹出成功信息窗口
     */
    public static void promoteSuccessAlertDialog(String msg){
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeight(250);
        alert.setHeaderText("提示");
        alert.setContentText(msg);
        alert.showAndWait();
    }

    /**
     * 弹出错误窗口
     * @param e
     */
    public static void promoteErrorAlertDialog(Exception e){
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeight(250);
        alert.setHeaderText("错误");
        alert.setContentText("程序运行时发生了一个错误：" + e.getMessage());
        GridPane content = createErrorExpandablePane(e);
        alert.getDialogPane().setExpandableContent(content);
        alert.showAndWait();
    }

    /**
     * 生成堆栈信息展示块
     * @param e
     * @return
     */
    private static GridPane createErrorExpandablePane(Exception e){
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        Label label = new Label("The exception stacktrace was:");
        TextArea textArea = new TextArea(stringWriter.toString());
        textArea.setEditable(false);
        textArea.setWrapText(true);
        textArea.setMaxWidth(Double.MAX_VALUE);
        textArea.setMaxHeight(Double.MAX_VALUE);
        GridPane.setVgrow(textArea,Priority.ALWAYS);
        GridPane.setHgrow(textArea, Priority.ALWAYS);

        GridPane gridPane = new GridPane();
        gridPane.setMaxWidth(Double.MAX_VALUE);
        gridPane.add(label, 0, 0);
        gridPane.add(textArea, 0, 1);
        return gridPane;
    }
}
